import { validateNull, isBlank } from "@/utils/validate";
import printJS from "print-js";

/**
 * 请求参数去重，并去掉$与空值
 */
export function paramsFilter(params) {
  if (validateNull(params)) return null;
  const res = {};
  const map = new Map(Object.entries(params));
  map.forEach((value, key) => {
    if (key.includes("$") || validateNull(value)) return;
    res[key] = value;
  });
  return res;
}

export function stringifyWithFunctions(object, custom?: boolean) {
  if (!custom) {
    return JSON.stringify(object);
  }
  return JSON.stringify(object, (key, val) => {
    if (key === "onLoad") {
      return `(${val})`;
    }
    if (["uploadPreview", "change", "focus", "click", "blur"].includes(key)) {
      return `${val}`;
    }
    return val;
  });
}

export function parseWithFunctions(obj: any, _this?) {
  if (!_this) {
    return parseWithString(obj);
  }
  return JSON.parse(obj, (key, val) => {
    if (key === "onLoad" || key === "uploadPreview") {
      return new Function(`return ${val};`).apply(_this);
    }
    return val;
  });
}

export function parseWithString(obj: string) {
  if (typeof obj === "string" && !isBlank(obj)) {
    return JSON.parse(obj);
  } else {
    return obj;
  }
}

export const printHtml = (id: string, header: string, data?: any) => {
  setTimeout(() => {
    printJS({
      type: "html",
      printable: id,
      header: header,
      targetStyles: ["*"],
      scanStyles: false
    });
    if (data) data.width = "-";
  }, 100);
};
